package com.kylin.module.user.orm;

import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.common.exception.BusinessException;
import com.kylin.module.user.orm.User;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.kylin.module.community.orm.Friendslist;
import org.hibernate.Query;
import java.util.Date;

/*
import org.hibernate.LockMode;
import org.hibernate.criterion.Example;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.exception.SystemException;
*/

/**
 * Data access object (DAO) for domain model class Friendslist.
 * @see 
 * @author mjj
 */
public class UserDAO extends BaseHibernateDAO {

    private static final Log log = LogFactory.getLog(UserDAO.class); 

    /*
     * 
     * 
     * 
     */
    
    public User login(String username, String password) {
        log.info("finding friends");
        try {
           String queryString = "from User as u where  u.active=1 and u.username = ? and u.password = ?";
           Query query = getSession().createQuery(queryString);
           query.setParameter(0, username);
           query.setParameter(1, password);
         //  query.setFirstResult(0);
         //  query.setMaxResults(10);
  		 //query.setParameter(0, value);
           log.info("size: "+ query.list().size());
           if (query.list().size() != 0){
        	   return (User)query.list().get(0);        	   
           }
  		 
        } catch (RuntimeException re) {
           log.error("find by property name failed", re);
           throw re;
        }
        return null;
  	}
    
    public boolean changePassword(User user, String password, String newpassword){
    	log.info("change password");
    	if(user == null){
    		log.info("please login firstly");
    		return false;
    	}
    	if (password == user.getPassword()){
    		user.setPassword(newpassword);
    		try{
    			super.saveOrUpdate(user);
    			return true;
    		}catch(BusinessException be){
    			log.info("business exception:"+be.toString());
    			return false;
    		}
    	}
    	return false;    	
    }
    
    public User findById( java.lang.Long id) {
        log.debug("getting User instance with id: " + id);
        try{
	        return (User)findById(User.class , id);
	    }
	    catch (BusinessException be){
	    	return null;
	    }
    }
    
}
